// 安装 Playwright 浏览器到本地可控目录，便于打包
// 约束：遵循工作区规则，不使用一行复杂命令，仅 Node 脚本

import { spawn } from 'node:child_process'
import { mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import process from 'node:process'

async function run(cmd, args, env = {}) {
  return await new Promise((resolve, reject) => {
    const child = spawn(cmd, args, {
      stdio: 'inherit',
      shell: process.platform === 'win32',
      windowsVerbatimArguments: process.platform === 'win32',
      cwd: process.cwd(),
      env: { ...process.env, ...env },
    })
    child.on('close', (code) => {
      if (code === 0)
        resolve(undefined)
      else reject(new Error(`${cmd} exited with code ${code}`))
    })
  })
}

async function main() {
  const target = join(process.cwd(), 'browsers')
  await mkdir(target, { recursive: true })

  // 让 Playwright 将浏览器安装到 app/browsers 目录
  const env = {
    PLAYWRIGHT_BROWSERS_PATH: target,
    PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '', // 允许下载
  }

  // 如果已经存在 Chromium 目录则跳过
  try {
    const { access } = await import('node:fs/promises')
    await access(join(target, 'chromium-1193'))
    return
  }
  catch {}

  // 仅安装 chromium，体积更小；直接调用本地二进制，避免 npx 兼容性问题
  // 使用 Node 直接运行 Playwright CLI，避免 .cmd 兼容问题
  const bin = join(process.cwd(), 'node_modules', '.bin', process.platform === 'win32' ? 'playwright.cmd' : 'playwright')
  await run(bin, ['install', 'chromium'], env)
}

main().catch((err) => {
  console.error('[install-playwright-browsers] 失败:', err)
  process.exit(1)
})
